package com.itlong.cloud.intercept;

import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.app.AppUserCacheVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.enumerate.ecode.MiniProgramErrorCodeEnum;
import com.itlong.cloud.user.miniprogram.IMiniProgramLoginServiceClient;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * <desc>
 *     小程序登录拦截器
 * </desc>
 * @createDate 2018/11/19
 */
@Aspect
@Component
public class LoginIntercept {
    private static final Logger LOG = LoggerFactory.getLogger(LoginIntercept.class);

 // 定义一个切入点
    @Pointcut("execution(* com.itlong.cloud.controller..*.*(..)) && !@annotation(com.itlong.cloud.annotation.UnAuthAccessRequired)")
    public void excudeService(){}

    @Value("${"+ PlatformConstants.WECHAT_MINI_USER_TOKEN_DONTINTERCEPT+"}")
    String dontIntercept;
    @Autowired
    IMiniProgramLoginServiceClient userCache;

    /**
     * <desc>
     *     用户token身份验证拦截器
     * </desc>
     * @param thisJoinPoint
     * @return
     * @throws Throwable
     * @author Qiang.S
     * @createDate 2018/11/26
     */
    @Around("excudeService()")
    public Object twiceAsOld(ProceedingJoinPoint thisJoinPoint) throws Throwable{
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String[] interceptMethod= StringHandlerUtil.splitString(dontIntercept);
        String uri = request.getRequestURI();
        System.out.println (String.format("【%s】请求路由:%s，客户端地址：%s", DateUtil.fomatDate1(new Date()), uri, HttpProtocolUtil.getIpAddr(request)));
        if (uri.indexOf("error") > -1 || uri.indexOf("404") > -1) {   //屏蔽错误中继续错误的死循环
            return thisJoinPoint.proceed();
        }
        //获取拦截方法的所有属性
        MethodSignature signature = (MethodSignature) thisJoinPoint.getSignature();
        //循环配置不需要拦截的方法
        for(String method:interceptMethod){
            if(signature.getMethod().getName().equals(method)){
                return thisJoinPoint.proceed();
            }
        }
        //获取token
        String token=request.getParameter("token");
        if (token == null) {
            token = request.getAttribute("token") == null ? null : request.getAttribute("token").toString();
        }
        if(StringUtils.isNotBlank(token)){
            //解密token拿到用户信息
            AppUserCacheVO userInfo=userCache.retrieveByCheckToken(token);
            if(userInfo==null){
                System.out.println("token已过期------"+token);
                    return new MessageVO(MiniProgramErrorCodeEnum.USER_TOKEN_ERROR.getErrorCode());
            }else{
                if (userInfo.getStatus()!=1){
                    return new MessageVO(MiniProgramErrorCodeEnum.USER_ACCOUNT_REFUSE.getErrorCode());
                }
                return thisJoinPoint.proceed();
            }
        }else{
            System.out.println("token为空------"+token);
            return new MessageVO(MiniProgramErrorCodeEnum.USER_TOKEN_ERROR.getErrorCode());
        }
    }
}
